/**
 * Created by Janpoem on 2016/2/1 0001.
 */

var config = require('./config');

var crypto = require('crypto');

var ivSize = 16;
var key = crypto.createHash('md5').update(config.cipherRawKey).digest();

var decrypt = function(data) {
	var hexData = new Buffer(data, 'hex');
	var length = hexData.length;
	var md5hash = hexData.slice(length - 16, length);
	var ivContent = hexData.slice(0, length - 16);
	var ivContentMd5Hash = crypto.createHash('md5').update(ivContent).digest();
	// check md5 hash at first
	if (ivContentMd5Hash.toString('utf8') !== md5hash.toString('utf8'))
		return false;

	var iv = ivContent.slice(0, 16);
	var content = ivContent.slice(16, ivContent.length);
	var decipher = crypto.createDecipheriv('aes-128-cbc', key, iv.toString('binary'));
	var dec = decipher.update(content,'hex','utf8');
	try {
		dec += decipher.final('utf8');
		return dec
	}
	catch (err) {
		return false;
	}
};

module.exports.decrypt = decrypt;